const jwt = require('jsonwebtoken')
const db = require('../models');
const User = db.User;

if (!User) {
  console.error('错误: User模型未正确定义');
  process.exit(1);
}

// 认证中间件
exports.authenticate = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '')
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '请提供认证令牌'
      })
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    const user = await User.findByPk(decoded.id)
    
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      })
    }

    req.user = user
    next()
  } catch (error) {
    console.error('认证失败:', error)
    res.status(401).json({
      success: false,
      message: '认证失败'
    })
  }
}

// 角色授权中间件
exports.authorize = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '无权访问此资源'
      })
    }
    next()
  }
}

// 邮箱验证检查
exports.verifiedOnly = (req, res, next) => {
  if (!req.user.isVerified) {
    return res.status(403).json({
      success: false,
      message: '请先验证邮箱'
    })
  }
  next()
}

// 管理员权限检查
exports.isAdmin = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({
      success: false,
      message: '无权访问此资源'
    })
  }
  next()
}